package local.eken.gfx.states.impl;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JPanel;

import local.eken.gfx.core.impl.IHandleView;

/**
 * Base class for view classes. These view classes are meant to be
 * states that the window changes to from certain commands.
 * ViewState gives the possibilities of drawing and handling key events.
 * @author Gabriel Ekblad
 *
 */
public abstract class ViewState extends JPanel {
	private static final long serialVersionUID = -8069846383342405259L;
	
	protected IHandleView view;

	public ViewState(IHandleView view) {
		this.view = view;
		this.setFocusable(true);
		this.addKeyListener(new ViewStateKeyAdapter());
	}
	
	/**
	 * Revalidates the state and sets the focus to the current state.
	 */
	public void revalidate() {
		this.setFocusable(true);
		
		if(!this.hasFocus()) {
			this.requestFocus();
		}
	}
	
	/**
	 * Draws the specific information from the different view
	 * states.
	 * @param canvas	The canvas to draw on
	 */
	public abstract void draw(Graphics2D canvas);
	
	/**
	 * Handles the state specific key events.
	 * @param e
	 */
	public abstract void handleKey(KeyEvent e);
	
	@Override
	public void paintComponent(Graphics g) {
		this.draw((Graphics2D) g);
	}
	
	private class ViewStateKeyAdapter extends KeyAdapter {
		@Override
		public void keyPressed(KeyEvent e) {
			switch(e.getKeyCode()) {
			case KeyEvent.VK_ESCAPE:
				ViewState.this.view.prevState();
				break;
			}
			
			ViewState.this.handleKey(e);
			ViewState.this.repaint();
		}
	}
}
